package com.camera.yl.v.models

import android.os.Environment
import android.util.Log
import android.view.View
import androidx.lifecycle.MutableLiveData
import com.camera.base.BaseApp
import com.camera.base.R
import com.camera.base.bean.CheckAppUpgradeResponse
import com.camera.base.inerface.DownloadCallback
import com.camera.base.net.listener.DownLoadInterface
import com.camera.base.net.listener.NetInterface
import com.camera.base.net.util.HttpCallback
import com.camera.base.util.APPUtil
import com.camera.base.util.ConfigSharePreferenceUtil
import com.camera.base.v.models.BaseViewModel
import com.camera.base.v.models.SystemNavBarViewModel
import com.camera.routemodule.routeinterface.IMAppInterface
import com.camera.routemodule.routeinterface.RouterUtil
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import javax.inject.Inject

@HiltViewModel
class MainViewModel @Inject constructor(
        var systemNavBarViewModel: SystemNavBarViewModel?, private val netInterface: NetInterface, private val downLoadInterface: DownLoadInterface
) : BaseViewModel(), CoroutineScope by MainScope(), DownloadCallback {
        val TAG = MainViewModel::class.java.simpleName
        val fragmentPttFrameLayoutVisible: MutableLiveData<Int> by lazy {
                MutableLiveData<Int>(View.GONE)
        }
        val rlMainTitleHeight: MutableLiveData<Int> by lazy {
                MutableLiveData<Int>(BaseApp.getApplication().resources.getDimensionPixelSize(R.dimen.qb_px_40))
        }
        val titleTextSize: MutableLiveData<Float> by lazy {
                MutableLiveData<Float>(BaseApp.getApplication().resources.getDimension(R.dimen.sp_px_20) /
                        BaseApp.getApplication().resources.displayMetrics.scaledDensity )
        }
        val sureTipsDialogEvent: MutableLiveData<Triple<Int, Int,String>> by lazy {
                MutableLiveData<Triple<Int, Int,String>>()
        }
        var mIMAppInterface: IMAppInterface? = null
        var path = ""
        init {
            mIMAppInterface = RouterUtil.getIMManagerImpl()
            mIMAppInterface.let {
                fragmentPttFrameLayoutVisible.value = View.VISIBLE
            }

            checkVersionUpgrade()
        }

        override fun onProgress(progress: Int) {
        }

        override fun onComplete() {
                ConfigSharePreferenceUtil.setUpgradeApkInLocal(true)
                sureTipsDialogEvent.postValue(Triple(1,1,"下载完成"))
        }

        override fun onFailure(error: String) {
        }

        override fun onCancel() {
        }

        override fun onPause() {
        }

        override fun onResume() {
        }
        fun extractDate(input: String?): String? {
                val regex = Regex("_\\d{8}_") // 正则表达式
                val matchResult = regex.find(input!!) // 查找匹配的部分
                return matchResult?.value?.removeSurrounding("_") // 去掉前后的下划线
        }

        fun checkVersionUpgrade() {
            launch {
                    if (ConfigSharePreferenceUtil.isAppUpgradeFrist()) {
                            //更新第一次  删除更新状态和文件
                            ConfigSharePreferenceUtil.setUpgradeApkInLocal(false);
                            //删除文件
                            if (ConfigSharePreferenceUtil.getUpgradeApk().isNotEmpty()) {
                                    File(ConfigSharePreferenceUtil.getUpgradeApk()).delete()
                            }
                            ConfigSharePreferenceUtil.setUpgradeApk("")
                            ConfigSharePreferenceUtil.setAppUpgradeFrist(false)
                    }
                    delay(10000)
                    netInterface.reqCheckForUpdateApp(CheckAppUpgradeResponse::class.java, object : HttpCallback<CheckAppUpgradeResponse>(){
                                        override fun onResult(var1: CheckAppUpgradeResponse?): Array<String?>? {
                                                if (!var1?.version.isNullOrEmpty()){
                                                        val remoteDate = extractDate(var1?.version)
                                                        val localDate = extractDate(APPUtil.getAppVersionName(BaseApp.getApplication()))
                                                        if (remoteDate!!.toInt() > localDate!!.toInt()){
                                                                //如果本地有完整的文件直接安装
                                                                if (ConfigSharePreferenceUtil.getUpgradeApkInLocal()) {
                                                                        path = ConfigSharePreferenceUtil.getUpgradeApk()
                                                                        if (File(path).exists()){
                                                                                sureTipsDialogEvent.postValue(Triple(1,1,"下载完成"))
                                                                        }else{
                                                                                ConfigSharePreferenceUtil.setUpgradeApkInLocal(false);
                                                                                path = Environment.getExternalStorageDirectory().absolutePath+File.separator+var1?.version+".apk"
                                                                                ConfigSharePreferenceUtil.setUpgradeApk(path)
                                                                                downLoadInterface.startDownload(BaseApp.ylBean.upgrade.appUpgradeUrl, path,this@MainViewModel)
                                                                        }
                                                                }else{
                                                                        //如果有路径说明 是之前下载过 可能下载到一半  并且 文件名跟服务器上的文件名是一样的
                                                                        val pathCache = ConfigSharePreferenceUtil.getUpgradeApk();
                                                                        Log.e(TAG, "onResult1111: ${File(pathCache).name}    - ${var1?.version}")
                                                                        if (!pathCache.equals("") && File(pathCache).name.equals(var1?.version+".apk")) {
                                                                                path = pathCache
                                                                                downLoadInterface.startDownload(BaseApp.ylBean.upgrade.appUpgradeUrl, pathCache,this@MainViewModel)
                                                                        }else{
                                                                                path = Environment.getExternalStorageDirectory().absolutePath+File.separator+var1?.version+".apk"
                                                                                ConfigSharePreferenceUtil.setUpgradeApk(path)
                                                                                downLoadInterface.startDownload(BaseApp.ylBean.upgrade.appUpgradeUrl, path,this@MainViewModel)
                                                                        }
                                                                }
                                                        }else{
                                                                if (ConfigSharePreferenceUtil.getUpgradeApk().isNotEmpty()) {
                                                                        File(ConfigSharePreferenceUtil.getUpgradeApk()).delete()
                                                                }
                                                                ConfigSharePreferenceUtil.setUpgradeApk("");
                                                                ConfigSharePreferenceUtil.setUpgradeApkInLocal(false);
                                                        }
                                                }
                                                return null
                                        }
                    })
            }
        }
}